// pages/pushList/pushList.js
const db = wx.cloud.database();
Page({
    /**
     * 页面的初始数据
     */
    data: {
      tabs: ['土地', '农具'],
      current:0,
      list: [],
      allChecked: false,
      totalNum: 0,
      openid:'',
    },

    tabSelect:function(e){
        var current = e.currentTarget.dataset.id
        this.setData({
            current:current,
        })
        this.getData(current);
    }, 

    async getData(e){
        var that = this;
        if(e == 0){
            await db.collection('land').where({
               'user._id':that.data.openid
            }).get().then(res=>{
                    var landlist = res.data;
                    for(var i =0;i<landlist.length;i++){
                       landlist[i].checked = false;
                    }
                    that.setData({
                        list:landlist
                    })
            })
        }else{
            await db.collection('tool').where({
                'user._id':that.data.openid
             }).get().then(res=>{
                     var toollist = res.data;
                     for(var i =0;i<toollist.length;i++){
                        toollist[i].checked = false;
                     }
                     that.setData({
                         list:toollist
                     })
             })
        }
     },
    
     onShow() {
         
        var u = wx.getStorageSync('userFlag'); 
        if(u.flag==0) {
            wx.showModal({
                title: '提示',
                content: '你还未完善个人信息，是否立刻去完善？',
                success (res) {
                    if (res.confirm) {
                        wx.switchTab({
                            url: '/pages/personal/personal',
                        })
                    } else if (res.cancel) {
                                wx.switchTab({
                                    url: '/pages/index/index',
                                })
                            }
                    }
            })
        }else{
            this.setData({
                openid:u.user._id,
            })
        }
        var{current} = this.data;
        this.getData(current);
     },
    
     goto(e){
      var str = e.currentTarget.dataset.record;
      var different = (this.data.current+1)%2
      wx.navigateTo({
        url: '/pages/show/show?jsonStr=' + encodeURIComponent(JSON.stringify(str))+'&condition='+ different,
      })
     },
      // 商品的选中
      handeItemChange(e) {
        const goods_id = e.currentTarget.dataset.id;
        let { list } = this.data;
        let index = list.findIndex(v => v._id === goods_id);
    
        list[index].checked = !list[index].checked;
    
        this.setCart(list);
      },
      setCart(list) {
        let allChecked = true;
    
        let totalNum = 0;
        list.forEach(v => {
          if (v.checked) {
            totalNum += 1;
          } else {
            allChecked = false;
          }
        })
        // 判断数组是否为空
        allChecked = list.length != 0 ? allChecked : false;
        this.setData({
            list,
           totalNum, 
           allChecked
        });
        
      },
    
      // 商品全选功能
      handleItemAllCheck() {
        // 1 获取data中的数据
        let { list, allChecked } = this.data;
        // 2 修改值
        allChecked = !allChecked;
        // 3 循环修改cart数组 中的商品选中状态
        list.forEach(v => v.checked = allChecked);
        // 4 把修改后的值 填充回data或者缓存中
        this.setCart(list);
      },
    
      async delete(){

        var that = this;
        const {current,totalNum}=this.data;
        // 2 判断用户有没有选购商品
        if(totalNum===0){
          wx.showToast({
              title:"您还没有选择任何记录",
              icon:'none'
            });
          return ;
        } 
        var {list} = this.data;
        var idlist = [];
        var imglist = [];
        var VRlist = [];
        list.forEach(element=>{
          if(element.checked){
            idlist.push(element._id);
            imglist.push(element.img);
            if(element.VR !== 0){
                VRlist.push(element.VR);
            }
          }
        })
        wx.showModal({
            title: '提示',
            content: '是否删除',
          async success (res) { 
              if (res.confirm) {
                wx.showLoading({
          title: '正在删除',
        })
        if(current == 0){
            for(var i =0;i<idlist.length;i++){
                await this.removeland(idlist[i])
                await this.removeimg(imglist[i]);
            }
            if(VRlist.length!==0){
                await this.removeVR(VRlist);
            }

        }else{
            for(var i =0;i<idlist.length;i++){
                await this.removetool(idlist[i])
                await this.removeimg(imglist[i]);
            }
            if(VRlist.length!==0){
                await this.removeVR(VRlist);
            }
        }
        
        wx.showToast({
          title: '成功删除',
        })
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
       
        
        await that.getData(current);
        let l = that.data.list;
        that.setCart(l);
      },
    
      async removeimg(imglist){

        await  wx.cloud.deleteFile({
            fileList: imglist
          }).then(res => {
            // handle success
          }).catch(error => {
            // handle error
          })
      },

      async removeVR(VRlist){
        await  wx.cloud.deleteFile({
            fileList: VRlist
          }).then(res => {
            // handle success
          }).catch(error => {
            // handle error
          })
      },
      async removeland(id){
          await db.collection('land').doc(id).remove().then(res=>{});
      },
      async removetool(id){
          await db.collection('tool').doc(id).remove().then(res=>{});
      },
      onPullDownRefresh:function () {
          
        setTimeout(()=>{ wx.stopPullDownRefresh({
        success: (res) => {}})},1000)  
    }
})